#!/bin/bash

source /home/shell/util.sh
source /home/shell/jenkins/jenkins-util.sh

update_site=https://jenkins-zh.gitee.io/update-center-mirror/tsinghua/update-center.json
update_base_site=https://mirrors.huaweicloud.com/jenkins/plugins

install_jenkins

# 设置端口
read -p "请输入Jenkins端口[8080]:" jenkins_port
jenkins_port=${jenkins_port:-"8080"};

source /etc/profile.d/java.sh


sed -ri "/candidates=/a\/opt/jdk/bin/java" /etc/rc.d/init.d/jenkins
sed -ri 's/JENKINS_PORT="8080"/JENKINS_PORT="'"${jenkins_port}"'"/g' /etc/sysconfig/jenkins

systemctl daemon-reload
/usr/lib/systemd/systemd-sysv-install enable jenkins


# 设置防火墙
firewall-addport $jenkins_port

# 启动服务
systemctl start jenkins

loadmsg_time=0;
while [ ! -f "/var/log/jenkins/jenkins.log" ]; do
  loadMsg "日志文件创建中..."
  sleep 1s 
done

loadmsg_time=0;
while [ -z "`tail /var/log/jenkins/jenkins.log|grep 'Jenkins is fully up and running'`" ]; do
  loadMsg "Jenkins服务启动中..."
  sleep 1s 
done

rm -rf /var/lib/jenkins/updates/default.json

for item in ${jenkins_plugins[*]}; do
  download /var/lib/jenkins/plugins/${item}.jpi ${update_base_site}/${item}/latest/${item}.hpi
done

# 设置插件中心
sed -ri "s#<url>https://updates.jenkins.io/update-center.json</url>#<url>"$update_site"</url>#" /var/lib/jenkins/hudson.model.UpdateCenter.xml
sed -ri "s/-Djava.awt.headless=true/-Djava.awt.headless=true -Dhudson.model.DownloadService.noSignatureCheck=true/g" /etc/sysconfig/jenkins
systemctl daemon-reload
systemctl restart jenkins

loadmsg_time=0;
while [ -z "`tail /var/log/jenkins/jenkins.log|grep 'Jenkins is fully up and running'`" ]; do
  loadMsg "Jenkins即将完成安装..."
  sleep 1s 
done

# 显示信息
printInfo "=====================jenkins====================="
printInfo "后台地址：http://$host_addr:$jenkins_port"
printInfo "初始密码："`cat /var/lib/jenkins/secrets/initialAdminPassword`
printInfo "插件中心：`cat /var/lib/jenkins/hudson.model.UpdateCenter.xml|grep url|sed -r 's#.*<url>(.*)</url>#\1#g'`"
printInfo "日志位置：/var/log/jenkins/jenkins.log"
printInfo "插件目录：/var/lib/jenkins/plugins/"
printInfo "=====================jenkins====================="